from sqlalchemy import desc, select
from sqlalchemy.exc import DBAPIError, IntegrityError

from poker_bot.core.exceptions.common import RepoError
from poker_bot.core.interfaces.account import AccountReader, AccountRepo
from poker_bot.core.models.dto.account import AccountDTO
from poker_bot.core.models.enums.account import AccountStatus
from poker_bot.database.converters.account import (
    convert_account_entity_to_db_model,
    convert_db_model_to_account_dto,
    convert_db_model_to_account_entity,
)
from poker_bot.database.exception_mapper import exception_mapper
from poker_bot.database.models import Account, User
from poker_bot.database.repositories.base import SQLAlchemyRepo
from poker_bot.domain.account import AccountEntity


class AccountReaderImpl(SQLAlchemyRepo, AccountReader):
    @exception_mapper
    async def get_account_by_id(self, account_id: int) -> AccountDTO | None:
        """Получаем пользователя по id"""

        account: Account | None = await self._session.scalar(
            select(Account).where(
                Account.id == account_id,
            )
        )
        if not account:
            return None

        return convert_db_model_to_account_dto(account)

    @exception_mapper
    async def get_user_accounts(self, user_tg_id: int) -> list[AccountDTO]:
        """Получаем аккаунты пользователя"""

        query = select(Account).join(Account.user).where(User.telegram_id == user_tg_id)

        res = await self._session.scalars(query)
        accounts: list[Account] = list(res)

        return [convert_db_model_to_account_dto(account) for account in accounts]

    @exception_mapper
    async def get_selected_user_account(self, user_tg_id: int) -> AccountDTO | None:
        """Получаем выбранный аккаунт пользователя"""

        account: Account | None = await self._session.scalar(
            select(Account)
            .join(Account.user)
            .where(
                Account.id == User.selected_account_id,
            )
        )
        if not account:
            return None

        return convert_db_model_to_account_dto(account)

    @exception_mapper
    async def get_accounts_for_confirmation(self) -> list[AccountDTO]:
        query = (
            select(Account)
            .where(Account.status == AccountStatus.on_moderation)
            .order_by(desc(Account.created_at))
        )

        res = await self._session.scalars(query)
        accounts: list[Account] = list(res)

        return [convert_db_model_to_account_dto(account) for account in accounts]


class AccountRepoImpl(SQLAlchemyRepo, AccountRepo):
    @exception_mapper
    async def acquire_account_by_id(self, account_id: int) -> AccountEntity | None:
        """Получаем пользователя по id"""

        account: Account | None = await self._session.scalar(
            select(Account)
            .where(
                Account.id == account_id,
            )
            .with_for_update()
        )
        if not account:
            return None

        return convert_db_model_to_account_entity(account)

    @exception_mapper
    async def create_user_account(self, account: AccountEntity) -> AccountEntity:
        db_account = convert_account_entity_to_db_model(account)
        self._session.add(db_account)
        try:
            await self._session.flush((db_account,))
        except IntegrityError as err:
            self._parse_error(err)

        return convert_db_model_to_account_entity(db_account)

    @exception_mapper
    async def update_account(self, account: AccountEntity) -> None:
        db_account = convert_account_entity_to_db_model(account)
        try:
            await self._session.merge(db_account)
        except IntegrityError as err:
            self._parse_error(err)

    @staticmethod
    def _parse_error(err: DBAPIError) -> None:
        raise RepoError from err
